package com.sharp.authorization.dao.common.repository;

import com.sharp.authorization.dao.common.entity.AcRolePermit;
import com.sharp.authorization.dao.common.mapper.AcRolePermitDao;
import com.sharp.kernel.mybatis.repository.BaseMysqlRepository;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Title: AcRolePermitService
 * Description: Copyright: Copyright (c) 2019 Company: BHFAE
 *
 * @author Sharp
 * @date 2022/6/16 14:20
 */
@Service
public class AcRolePermitService extends BaseMysqlRepository<AcRolePermit, AcRolePermitDao> {

    @Resource
    private AcRolePermitDao acRolePermitDao;

    public void deleteByRoleId(String roleId) {
        Example example = buildExample(roleId, null);
        super.delete(example);
    }

    private Example buildExample(String roleId, String permitId) {
        Example example = getExample();
        Example.Criteria criteria = example.createCriteria();
        if (roleId != null) {
            criteria.andEqualTo("roleId", roleId);
        }
        if (permitId != null) {
            criteria.andEqualTo("permitId", permitId);
        }
        return example;
    }

    public void deleteByPermitId(String permitId) {
        Example example = buildExample(null, permitId);
        super.delete(example);
    }

    public int countByPermitId(String permitId) {
        Example example = buildExample(null, permitId);
        return super.count(example);
    }

    public void bind(String roleId, List<String> permitIdList) {
        List<AcRolePermit> list = new ArrayList<>();
        for (String permitId : permitIdList) {
            AcRolePermit rolePermit = buildRolePermit(permitId, roleId);
            list.add(rolePermit);
        }
        super.insertBatch(list);
    }

    private AcRolePermit buildRolePermit(String permitId, String roleId) {
        AcRolePermit rolePermit = new AcRolePermit();
        rolePermit.setPermitId(permitId);
        rolePermit.setRoleId(roleId);
        return rolePermit;
    }

}
